#encoding: utf-8
class OsseanHighchartsController < ApplicationController
  def index
    @whichChart = params[:whichChart]
    if @whichChart == '1' || @whichChart == nil
      #第一组图
      #记录开源项目id
      @chart1_open_source_project = []
      @chart1_avg_min_salary = []
      @chart1_avg_max_salary = []
      @chart1_experience = []
      #获取所有osp_id以及该id对应的匹配帖子数目
      highcharts_ospId_countItems =  Highchart.find(:all, :select => "distinct osp_id, count(*) as num", :group => "osp_id")
      highcharts_ospId_countItems = sortHighchartByItemsDesc(highcharts_ospId_countItems,20)
      #获取随机数字代表下表的Highchart对象
      highcharts_ospId_countItems.each do |h|
        ospId = h.osp_id
        osp_find_result = OpenSourceProject.find(ospId)#根据项目id获取项目对象
        @chart1_open_source_project << osp_find_result
        experience_result = Highchart.find(:all, :conditions => ["osp_id=? and experience != ''",ospId], :select => "distinct experience")
        experience_result = sortHighchartByExperienceAsc(experience_result)
        experience_tmp = []
        avg_min_salary_tmp = []
        avg_max_salary_tmp = []
        experience_result.each do |experience|
          if experience.experience == ""
            experience_tmp << "没经验"
          else
            experience_tmp << experience.experience
          end
          min_find_result = Highchart.find(:first, :select => "avg(min_salary) as avg_min", :conditions => ["osp_id=? and experience=?",ospId,(experience.experience).to_s])
          max_find_result = Highchart.find(:first, :select => "avg(max_salary) as avg_max", :conditions => ["osp_id=? and experience=?",ospId,(experience.experience).to_s])
          avg_min_salary_tmp << min_find_result.avg_min.to_f
          avg_max_salary_tmp << max_find_result.avg_max.to_f
        end
        @chart1_experience << experience_tmp
        @chart1_avg_min_salary << avg_min_salary_tmp
        @chart1_avg_max_salary << avg_max_salary_tmp
      end
      elsif @whichChart == '2'
        #第二组图(不同地区各开源软件的平均最高和最低工资)
        @chart2_open_source_project_name = []
        @chart2_city = []
        @chart2_avg_min_salary = []
        @chart2_avg_max_salary = []
        #读取所有的city以及对应的count(*)
        highcharts_city_countItems = Highchart.find(:all, :conditions => "city is not null", :select => "city, count(*) as num", :group => "city")
        highcharts_city_countItems = sortHighchartByItemsDesc(highcharts_city_countItems,20)
        highcharts_city_countItems.each do |h|
          city = h.city
          @chart2_city << city
          #根据city找最热门的10个软件
          highcharts_ospId_countItemsBycity = Highchart.find(:all, :conditions => ["city=?",city], :select => "osp_id, count(*) as num", :group => 'osp_id')
          highcharts_ospId_countItemsBycity = sortHighchartByItemsDesc(highcharts_ospId_countItemsBycity,10)
          osp_results_tmp = []
          avg_min_salary_tmp = []
          avg_max_salary_tmp = []
          highcharts_ospId_countItemsBycity.each do |h2|
            ospId = h2.osp_id
            osp_results_tmp << OpenSourceProject.find(ospId).name
            #根据osp_id和city获取平均最高和最低工资
            highchart_avgMinSalary = Highchart.find(:first, :conditions => ["osp_id=? and city=?", ospId,city], :select => "avg(min_salary) as avg_min_salary")
            highchart_avgMaxSalary = Highchart.find(:first, :conditions => ["osp_id=? and city=?", ospId,city], :select => "avg(max_salary) as avg_max_salary")
            avg_min_salary_tmp << (highchart_avgMinSalary.avg_min_salary).to_f
            avg_max_salary_tmp << (highchart_avgMaxSalary.avg_max_salary).to_f
          end
          @chart2_open_source_project_name << osp_results_tmp
          @chart2_avg_min_salary << avg_min_salary_tmp
          @chart2_avg_max_salary << avg_max_salary_tmp
        end
      elsif @whichChart == '3'
        #第三组图(开源软件职位需求数量)
        @chart3_open_source_project_name = []
        @chart3_require = []
        highcharts_ospId_countItems = Highchart.find(:all, :select => "osp_id, count(*) as num", :group => "osp_id")
        highcharts_ospId_countItems = sortHighchartByItemsDesc(highcharts_ospId_countItems,20)
        highcharts_ospId_countItems.each do |h|
          ospId = h.osp_id
          @chart3_open_source_project_name << OpenSourceProject.find(ospId).name
          highcharts_require = Highchart.find(:first, :select => "count(*) as num", :conditions => ["osp_id=?",ospId])
          @chart3_require << highcharts_require.num.to_i
        end
      elsif @whichChart == '4'
        #@chart4_city = []
        #获取所有的city
        #highcharts_city = Highchart.find(:all, :select => 'distinct city', :conditions => 'city is not null')
        #构造select下拉列表显示
        # highcharts_city.each do |h|
          # city = h.city.to_s
          # data = [city,city]
          # @chart4_city << data
        # end
        @chart4_city = Highchart.find(:all, :select => 'distinct city', :conditions => 'city is not null', :order => 'city asc')
    end    
  end
  
  
    
  def ajax
    chart = params[:chart].to_i
    if chart == 4
      dataArray = []
      data2Array = []
      ospIdArray = []
      experienceArray = []
      countArray = []
      count2Array = []
      range3Array = []
      city = params[:city]
      highcharts_osp_id_count = Highchart.find(:all, :select => 'osp_id,count(*) as num', :conditions => ['city=?',city], 
                                          :group => 'osp_id', :order => 'num desc')
      if highcharts_osp_id_count.length == 0
        dataArray = nil
      else
        countSum = 0
        highcharts_osp_id_count.each do |h|
          osp_id = h.osp_id.to_i
          count = h.num.to_i
          countSum = countSum + count
          ospIdArray << osp_id
          countArray << count
        end
        #计算所有百分比大于等于5%的
        sumRate = 0.0
        for i in (0..ospIdArray.length - 1)
          osp_id = ospIdArray[i]
          count = countArray[i]
          rate = count * 1.0 / countSum * 100
          if rate >= 1
            sumRate = sumRate + rate
            #读取开源项目名
            begin
              osp = OpenSourceProject.find(osp_id)
            rescue Exception => e
              osp = nil #没有读取到osp 数据问题 做异常处理
            end
            if !osp.nil?
              osp_name = OpenSourceProject.find(osp_id).name.to_s
              if !osp_name.nil?
                data = [osp_name,rate]
                dataArray << data
              end
            end
          end
        end
        #看有没有others选项
        if dataArray.length < ospIdArray.length
          othersRate = 100 - sumRate
          data = ['其他', othersRate]
          dataArray << data
        end
        
        #查找experience字段
        highcharts_experience_count = Highchart.find(:all, :select => 'experience,count(*) as num', :conditions => ['city=? and experience!=?',city,''], 
                                          :group => 'experience', :order => 'num desc')
        if highcharts_experience_count.length == 0
          data2Array = nil
        else
          countSum = 0
          highcharts_experience_count.each do |h|
            experience = h.experience.to_s
            count = h.num.to_i
            experienceArray << experience
            count2Array << count
            countSum = countSum + count
          end
          #计算占有率
          for i in (0..experienceArray.length - 1)
            rate = count2Array[i] * 1.0 / countSum * 100
            data = [experienceArray[i],rate]
            data2Array << data
          end
        end
        
        #查找当前地区和experience对应的avg_salary_min/max
        experienceArray.each do |experience|
          highchart_avg_min_max_salary = Highchart.find(:first, :select => 'avg(min_salary) as avg_min_salary, avg(max_salary) as avg_max_salary', :conditions => ['city=? and experience=?',city,experience])
          avg_min_salary = highchart_avg_min_max_salary.avg_min_salary.to_i
          avg_max_salary = highchart_avg_min_max_salary.avg_max_salary.to_i
          range = [avg_min_salary,avg_max_salary]
          range3Array << range
        end
      end
    end
    respond_to do |format|
        format.json {render :json => {:city => city, :data => dataArray, :data2 => data2Array, :experience => experienceArray, :range3 => range3Array}}
    end
  end
  
  private
  #定义生成随机数的函数 k-生成k个 m-最大值为m(≤m)
  def generateRand(k,m)
    result = []
    while result.length < k
      tmp = rand(m+1)
      result << tmp
      result.uniq!
    end
    return result
  end
  
  #根据项目匹配帖子数量对Highchart对象进行从大到小排序
  def sortHighchartByItemsDesc(highcharts, k)
    nums = []#用于记录highchart对象中的num数值
    results = []
    highcharts.each do |h|
      n = h.num.to_i
      if nums.length == 0
        nums << n
        results << h
      else
        for i in (0..nums.length-1)
          if n > nums[i]
            nums.insert(i, n)#在下标i之前插入元素
            results.insert(i, h)
            break
          elsif i == nums.length - 1
            #表示比较到末尾还没有满足条件
            nums << n
            results << h
            break
          end
        end
      end
      
      #将大于20的下标后面的元素去除
      if results.length > k
        results = results[0,k]
        nums = nums[0,k]
      end
    end
    results.each do |r|
      tmp = r.num.to_i
    end
    return results
  end
  
   #对experience进行排序
  def sortHighchartByExperienceAsc(highcharts)
    #0:没有要求 1:应届毕业生 2:1-3年经验 3:3-5年经验 4:5-10年经验 5:10年以上经验
    results = Array[nil,nil,nil,nil,nil,nil]
    highcharts.each do |h|
      experience = (h.experience).to_s
      if experience == ""
        results[0] = h
      elsif experience == "经验应届毕业生"
        results[1] = h
      elsif experience == "经验1-3年"
        results[2] = h
      elsif experience == "经验3-5年"
        results[3] = h
      elsif experience == "经验5-10年"
        results[4] = h
      elsif experience == "经验10年以上"
        results[5] = h
      end
    end
    results.compact!
    return results

  end
end
